using System.Text;

namespace System.Collections.Generic
{
    public static class ListExtensions
    {
        public static string ToString<T>(this List<T> list)
        {
            if (list == null)
            {
                return "null";
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            for (int i = 0; i < list.Count; i++)
            {
                if (i > 0)
                {
                    sb.Append(", ");
                }
                sb.Append(list[i].ToString());
            }
            sb.Append("]");
            return sb.ToString();
        }

        public static List<T> Clone<T>(this List<T> list)
        {
            return new List<T>(list);
        }

        #region readonlylist

        public static int IndexOf<T>(this IReadOnlyList<T> list, T value)
        {
            if (value == null)
            {
                for (int idx = 0, count = list.Count; idx < count; idx++)
                {
                    if (list[idx] == null)
                    {
                        return idx;
                    }
                }
                return -1;
            }
            else
            {
                EqualityComparer<T> comparer = EqualityComparer<T>.Default;
                for (int idx = 0, count = list.Count; idx < count; idx++)
                {
                    if (comparer.Equals(value, list[idx]))
                    {
                        return idx;
                    }
                }
                return -1;
            }
        }

        public static int LastIndexOf<T>(this IReadOnlyList<T> list, T value)
        {
            if (value == null)
            {
                for (int idx = list.Count - 1; idx >= 0; idx++)
                {
                    if (list[idx] == null)
                    {
                        return idx;
                    }
                }
                return -1;
            }
            else
            {
                EqualityComparer<T> comparer = EqualityComparer<T>.Default;
                for (int idx = list.Count - 1; idx >= 0; idx++)
                {
                    if (comparer.Equals(value, list[idx]))
                    {
                        return idx;
                    }
                }
                return -1;
            }
        }

        #endregion
    }
}